<template>
  <div class="search-results">
    <div class="search-header" v-if="getTotalSearchCount() > 0">
      <h2 class="search-title">
        <el-icon><Search /></el-icon>
        <span>搜索结果：共找到 {{ getTotalSearchCount() }} 个网站</span>
      </h2>
    </div>
    
    <template
      v-for="category in menuList"
      :key="category.oneMenuId"
    >
      <div
        v-if="hasSearchResults(category)"
        class="search-category-group"
      >
      <!-- 一级菜单标题 -->
      <div class="category-header">
        <div class="category-icon">
          <svg class="icon-svg" aria-hidden="true">
            <use :xlink:href="category.icon"></use>
          </svg>
        </div>
        <h2 class="category-title">{{ category.oneMenuName }}</h2>
        <div class="category-count">
          {{ getCategorySearchCount(category) }} 个结果
        </div>
      </div>

      <!-- 二级菜单分组展示 -->
      <template
        v-for="subCategory in category.twoMenuList"
        :key="subCategory.twoMenuId"
      >
        <div
          v-if="subCategory.websiteList.length > 0"
          class="search-subcategory-group"
        >
        <h3 class="subcategory-title">{{ subCategory.twoMenuName }}</h3>
        <div class="website-grid">
          <div
            v-for="site in subCategory.websiteList"
            :key="site.id"
            class="website-card"
            @click="handleWebsiteClick(site)"
          >
            <a :href="site.websiteUrl" target="_blank" class="website-link">
              <div class="website-card-content">
                <div class="website-icon">
                  <img
                    :src="getLogoUrl(site.websiteLogo)"
                    :alt="site.websiteName"
                    @error="handleImageError"
                    loading="lazy"
                  />
                </div>
                <div class="website-info">
                  <h4 class="website-name">{{ site.websiteName }}</h4>
                  <p class="website-desc">
                    {{ site.websiteRemark || '暂无描述' }}
                  </p>
                </div>
                <div class="website-stats">
                  <div class="stats-left">
                    <el-icon><View /></el-icon>
                    <span class="visit-count">{{ formatNumber(site.websiteClickNum) }} 次访问</span>
                  </div>
                </div>
              </div>
            </a>
          </div>
        </div>
        </div>
      </template>
    </div>
    </template>

    <!-- 搜索结果为空 -->
    <div v-if="getTotalSearchCount() === 0 && !loading" class="search-empty">
      <el-empty description="未找到相关网站，请尝试其他关键词" :image-size="200" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { Search, View } from '@element-plus/icons-vue'
import type { MenuWebsiteVO, WebsiteDetail } from '@/interfaces/data'
import { addWebsiteClick } from '@/api/websiteClick'

/**
 * Props 定义
 */
const props = defineProps<{
  /** 菜单网站数据列表（搜索结果） */
  menuList: MenuWebsiteVO[]
  /** 加载状态 */
  loading: boolean
}>()

/**
 * Emits 定义
 */
const emit = defineEmits<{
  /** 网站被点击 */
  'website-click': [site: WebsiteDetail]
}>()

/**
 * 获取搜索结果总数
 * @returns 搜索结果总数
 */
function getTotalSearchCount(): number {
  return props.menuList.reduce((total, category) => {
    return total + getCategorySearchCount(category)
  }, 0)
}

/**
 * 获取某个分类的搜索结果数量
 * @param category 一级分类
 * @returns 该分类下的搜索结果数量
 */
function getCategorySearchCount(category: MenuWebsiteVO): number {
  return category.twoMenuList.reduce(
    (total, sub) => total + sub.websiteList.length,
    0
  )
}

/**
 * 判断分类是否有搜索结果
 * @param category 一级分类
 * @returns 是否有搜索结果
 */
function hasSearchResults(category: MenuWebsiteVO): boolean {
  return getCategorySearchCount(category) > 0
}

/**
 * 获取Logo URL
 * 处理相对路径和绝对路径
 * @param logo Logo路径
 * @returns 完整的Logo URL
 */
function getLogoUrl(logo: string): string {
  if (!logo) {
    return '/api/favicon.ico'
  }
  if (logo.startsWith('http://') || logo.startsWith('https://')) {
    return logo
  }
  return `/api/${logo}`
}

/**
 * 处理图片加载错误
 * 当Logo加载失败时，使用默认图标
 */
function handleImageError(event: Event) {
  const img = event.target as HTMLImageElement
  img.src = '/api/favicon.ico'
}

/**
 * 格式化数字显示
 * 大于1000的数字显示为K单位
 * @param num 数字
 * @returns 格式化后的字符串
 */
function formatNumber(num: number): string {
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  }
  return num.toString()
}

/**
 * 处理网站点击事件
 * 记录点击数据并更新网站点击数
 * @param site 网站详情
 */
function handleWebsiteClick(site: WebsiteDetail) {
  const clickData = {
    id: '', // 点击记录的id，后端自动生成，传空字符串即可
    menuName: site.menuName,
    websiteName: site.websiteName,
    websiteId: site.id || null, // 传递网站ID，用于准确更新网站点击数
    clickTime: '',
    browserInfo: navigator.userAgent,
    osInfo: navigator.platform,
  }
  addWebsiteClick(clickData).catch(() => {
    // 静默失败，不影响用户体验
  })
  emit('website-click', site)
}
</script>

<style scoped lang="scss">
.search-results {
  .search-header {
    margin-bottom: 32px;
    padding-bottom: 16px;
    border-bottom: 2px solid var(--theme-border);
  }

  .search-title {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 24px;
    font-weight: 600;
    color: var(--theme-text);
    margin: 0;

    .el-icon {
      color: var(--theme-primary);
      font-size: 28px;
    }
  }

  .search-category-group {
    margin-bottom: 48px;
    animation: fadeInUp 0.5s ease-out;
  }

  .search-subcategory-group {
    margin-bottom: 32px;

    .subcategory-title {
      font-size: 18px;
      font-weight: 600;
      color: var(--theme-text-secondary);
      margin: 0 0 16px 0;
      padding-left: 16px;
      border-left: 4px solid var(--theme-primary);
      position: relative;

      &::before {
        content: '';
        position: absolute;
        left: -4px;
        top: 0;
        bottom: 0;
        width: 4px;
        background: var(--theme-gradient);
        border-radius: 2px;
      }
    }
  }

  .search-empty {
    margin: 80px 0;
    text-align: center;
  }

  // 搜索模式下使用与正常模式一致的分类标题样式
  .category-header {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 2px solid var(--theme-border);
  }

  .category-icon {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--theme-gradient);
    border-radius: 10px;

    .icon-svg {
      width: 24px;
      height: 24px;
      color: #ffffff;
    }
  }

  .category-title {
    flex: 1;
    font-size: 28px;
    font-weight: 600;
    color: var(--theme-text);
    margin: 0;
  }

  .category-count {
    font-size: 14px;
    color: var(--theme-text-secondary);
    padding: 6px 16px;
    background: rgba(102, 126, 234, 0.15);
    color: var(--theme-primary);
    border-radius: 16px;
    font-weight: 600;
  }

  /* 网站网格 */
  .website-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
  }

  .website-card {
    background: var(--theme-card-bg);
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    cursor: pointer;
    border: 1px solid var(--theme-border);
    position: relative;
    height: 100%;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 4px;
      background: var(--theme-gradient);
      transform: scaleX(0);
      transform-origin: left;
      transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    }

    &:hover {
      transform: translateY(-6px);
      box-shadow: 0 12px 32px rgba(102, 126, 234, 0.25);
      border-color: var(--theme-primary);

      &::before {
        transform: scaleX(1);
      }

      .website-icon {
        transform: scale(1.1);
        box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
      }

      .website-icon img {
        transform: scale(1.05);
      }
    }
  }

  .website-link {
    text-decoration: none;
    color: inherit;
    display: block;
    height: 100%;
  }

  .website-card-content {
    padding: 24px;
    display: flex;
    flex-direction: column;
    gap: 16px;
    height: 100%;
  }

  .website-icon {
    width: 64px;
    height: 64px;
    border-radius: 16px;
    background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    align-self: flex-start;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;

    &::after {
      content: '';
      position: absolute;
      inset: 0;
      border-radius: 16px;
      padding: 2px;
      background: linear-gradient(135deg, var(--theme-primary), var(--theme-secondary));
      -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
      -webkit-mask-composite: xor;
      mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
      mask-composite: exclude;
      opacity: 0;
      transition: opacity 0.4s ease;
    }

    img {
      width: 56px;
      height: 56px;
      border-radius: 12px;
      object-fit: cover;
      transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    }
  }

  .website-card:hover .website-icon::after {
    opacity: 1;
  }

  .website-info {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .website-name {
    font-size: 18px;
    font-weight: 700;
    color: var(--theme-text);
    margin: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-height: 1.4;
    transition: color 0.3s ease;
  }

  .website-card:hover .website-name {
    color: var(--theme-primary);
  }

  .website-desc {
    font-size: 14px;
    color: var(--theme-text-secondary);
    margin: 0;
    line-height: 1.6;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    min-height: 44px;
  }

  .website-stats {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
    padding-top: 12px;
    margin-top: auto;
    border-top: 1px solid var(--theme-border);
    font-size: 12px;
    color: #909399;

    .stats-left {
      display: flex;
      align-items: center;
      gap: 6px;
    }

    .el-icon {
      font-size: 14px;
      color: var(--theme-primary);
    }

    .visit-count {
      font-weight: 500;
      color: var(--theme-text-secondary);
    }
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>

